import Vue from "vue";
const api = window.$api.data.area;
const area = {
  namespaced: true,
  state: {
    map: {},
    loadState: {},
  },
  actions: {
    async load({ commit, state }, { pid, isCache }) {
      if (!state.loadState[pid] || !isCache) {
        state.loadState[pid] = true;
        const res = await api.getList(pid);
        const data = res.data.data;
        data.forEach((ele) => {
          if (ele.f_Layer != 4) {
            ele.hasChildren = true;
          }
        });
        commit("SET_AREAS", { pid: pid, areas: data });
      }
    },
    add({ commit }, formData) {
      return new Promise((resolve, reject) => {
        api
          .add(formData)
          .then((res) => {
            formData.f_AreaId = res.data.data;
            commit("ADD_AREA", formData);
            resolve(res);
          })
          .catch((err) => {
            //console.log(err)
            reject(err);
          });
      });
    },
    update({ commit }, payload) {
      return new Promise((resolve, reject) => {
        api
          .update(payload.id, payload.formData)
          .then((res) => {
            commit("UPDATE_AREA", payload);
            resolve(res);
          })
          .catch((err) => {
            //console.log(err);
            reject(err);
          });
      });
    },
    remove({ commit }, payload) {
      return new Promise((resolve, reject) => {
        api
          .remove(payload.id)
          .then((res) => {
            commit("DELETE_AREA", payload);
            resolve(res);
          })
          .catch((err) => {
            //console.log(err);
            reject(err);
          });
      });
    },
    get({ state }, key) {
      return new Promise((resolve) => {
        let node = null;
        for (let id in state.map) {
          node = state.map[id].find((t) => t.f_AreaId == key);
          if (node) {
            break;
          }
        }
        resolve(node);
      });
    },
  },
  mutations: {
    SET_AREAS: (state, payload) => {
      Vue.set(state.map, payload.pid, payload.areas);
    },
    ADD_AREA: (state, payload) => {
      state.map[payload.f_ParentId] = state.map[payload.f_ParentId] || {};
      state.map[payload.f_ParentId] && state.map[payload.f_ParentId].push(payload);
    },
    UPDATE_AREA: (state, payload) => {
      const list = state.map[payload.oldPid];
      list.splice(
        list.findIndex((item) => {
          return item.f_AreaId == payload.id;
        }),
        1
      );
      state.map[payload.formData.f_ParentId] && state.map[payload.formData.f_ParentId].push(payload.formData);
    },
    DELETE_AREA: (state, payload) => {
      var list = state.map[payload.pid];
      list.splice(
        list.findIndex((item) => {
          return item.f_AreaId == payload.id;
        }),
        1
      );
    },
  },
};
export default area;
